// components/my/my.js
import Api from '../../utils/Api'
import Config from '../../utils/Config'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    userInfo: {
      type: [Object, String]
    },
    isLogin: {
      type: Boolean
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    activeNav:0,
    recipeList:[],
    recipeTypeList:[],
    followList:[],
    recipeListConfig:{
      nowPage:0, // 当前读取到的页数
      maxLimit:20 // 每页获取的数据条数
    },
    followListConfig:{
      nowPage:0, // 当前读取到的页数
      maxLimit:20 // 每页获取的数据条数
    },
    menuBtns:[
        {
          type: 'warn',
          text: '删除',
          extClass: 'test',
          src: '/page/weui/cell/icon_del.svg', // icon的路径
        }
    ],
    followBtns:[
      {
        type: 'warn',
        text: '取消关注',
        extClass: 'test',
        src: '/page/weui/cell/icon_del.svg', // icon的路径
      }
    ],
    state:false
  },
  // 组件初始化
  ready(){
    this.setData({state:wx.getStorageSync('state')},()=>{
      console.log(this.data.state);
    });
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 登陆操作
    saveUserInfo(e) {
      if (e.detail.userInfo) {
        wx.login({
          success: (res) => {
            // 获取openid
            wx.cloud.callFunction({
              name: 'login',
              success: async (res) => {
                // console.log(res);
                var _openid = res.result.openid;
                var userInfo = e.detail.userInfo;
                userInfo.isAdmin = false;
                Api.filterData(Config.tableName.userTable, {
                  _openid
                }).then(res => {
                  // 判断是否有数据
                  if (!res.data.length) {
                    Api.addData(Config.tableName.userTable, {
                      userInfo
                    })
                  }else{
                    userInfo = res.data[0].userInfo
                  }
                  wx.showToast({
                    title: '登陆成功',
                  })
                  this.triggerEvent('loginevent', {
                    userInfo
                  }, {
                    a: 1
                  })
                  // 将数据存储在本地
                  wx.setStorageSync('_openid', _openid);
                  wx.setStorageSync('userInfo', userInfo);
                  this.getMyData();
                })
              }
            })
          }
        })
      } else {
        wx.showToast({
          title: '登陆失败',
          icon: 'none'
        })
      }
    },
    // 点击头像跳转
    jumpTo(){
      console.log(this.properties.userInfo.isAdmin)
      if(this.properties.userInfo.isAdmin){
        wx.navigateTo({
          url: '../../pages/pdmenutype/pdmenutype',
        })
      }
    },
    // 获取页面数据
    getMyData(){
      // 加载我的菜谱数据
      if(this.data.activeNav==0){
        this.getRecipeList('update');
      }
      // 加载我的菜谱分类数据
      else if(this.data.activeNav==1){
        this.getRecipeType();
      }
      // 加载我关注的菜谱信息
      else{
        this.getFollowRecipe('update');
      }
    },
    // 切换导航
    changeNav(e){
      this.setData({
        activeNav:e.currentTarget.dataset.index
      });
      // 获取数据
      // 判断是否登陆了
      let _openid = wx.getStorageSync('_openid');
      if(_openid){
        this.getMyData('update');
      }
    },
    // 获取菜谱信息
    async getRecipeList(type){
      // 判断是获取还是更新数据
      if(type=='update'){
        // 重置获取配置
        this.data.recipeListConfig.nowPage = 0;
        this.setData({
          recipeListConfig:this.data.recipeListConfig
        });
      }
      // 获取openid
      var _openid = wx.getStorageSync('_openid');
      // console.log(_openid)
      // 获取数据
      // 获取limit
      let limit = this.data.recipeListConfig.maxLimit;
      // 计算skip
      let skip = this.data.recipeListConfig.nowPage * limit;
      // nowPage加一
      this.data.recipeListConfig.nowPage++;
      this.setData({
        recipeListConfig:this.data.recipeListConfig
      })
      var recipeList = (await Api.getLimitData({tableName:Config.tableName.recipesTable,skip,limit,where:{_openid,status:1}})).data;
      console.log(_openid,recipeList)
      // 判断是获取还是更新数据
      console.log(type)
      if(type=='addGet'){
        this.setData({
          recipeList:this.data.recipeList.concat(recipeList)
        });
      }else if(type=='update'){
        console.log('update')
        this.setData({
          recipeList
        });
      }
    },
    // 获取我的菜谱分类
    async getRecipeType(){
      // 获取我的菜谱的全部分类id
      let typeIdList = this.data.recipeList.map(item=>{
        return item.recipeTypeId
      });
      // 判断是否为空
      if(typeIdList.length==0){
        return;
      }
      // 去重
      typeIdList = [...new Set(typeIdList)];
      console.log(typeIdList);
      // 获取操作符
      const _ = Api.db.command;
      // 设置筛选条件
      let filterTypeList = _.or(typeIdList[0]);
      for(let i = 1; i < typeIdList.length; i++){
        filterTypeList = filterTypeList.or(typeIdList[i]);
      }
      console.log(filterTypeList);
      // 通过id获取分类信息
      let recipeTypeList = (await Api.filterData(Config.tableName.recipeType,{_id:filterTypeList})).data;
      // console.log(recipeTypeList);
      this.setData({
        recipeTypeList
      });
    },
    // 获取关注的菜谱列表
    async getFollowRecipe(type){
      // 判断是获取还是更新数据
      if(type=='update'){
        // 重置获取配置
        this.data.followListConfig.nowPage = 0;
        this.setData({
          followListConfig:this.data.followListConfig
        });
      }
      // 获取用户关注的列表
      let followList = (await wx.cloud.callFunction({
        name:'getLimitData',
        data:{
          tableName:Config.tableName.followTable,
          where:{
            _openid:wx.getStorageSync('_openid')
          },
          sort:{
            createDate:-1
          },
          lookup:{from:Config.tableName.recipesTable,localField:'recipeid',foreignField:'_id',as:'recipeList'}
        }
      })).result.list;
      // 判断是获取还是更新数据
      console.log(followList)
      if(type=='addGet'){
        this.setData({
          followList:this.data.followList.concat(followList)
        });
      }else if(type=='update'){
        // console.log('update')
        this.setData({
          followList
        });
      }
    },
    // 删除菜谱 将其状态修改为0
    delRecipe(e){
      console.log(e.currentTarget.dataset)
      let _id = e.currentTarget.dataset._id;
      wx.showModal({
        cancelColor: 'cancelColor',
        title:'删除提示',
        content:'确认要删除吗？'
      }).then(async res=>{
        if(res.confirm){
          var delResult = await Api.updateById(Config.tableName.recipesTable,_id,{status:0});
          if(delResult.stats.updated > 0){
            wx.showToast({
              title: '删除成功！'
            });
            // 获取删除的数据在本地的索引
            let index = this.data.recipeList.findIndex(item=>{
              return item._id == _id;
            })
            // 在本地删除
            this.data.recipeList.splice(index,1);
            this.setData({
              recipeList:this.data.recipeList
            })
          }
          console.log(delResult)
        }
      })
    },
    // 取消关注
    async unFollow(e){
      console.log(e.currentTarget.dataset._id);
      // 删除关注
      let result = await Api.delById(Config.tableName.followTable,e.currentTarget.dataset._id);
      if(result.stats.removed > 0){
        Api.updateById(Config.tableName.recipesTable,e.currentTarget.dataset.recipeid, {
          follows: Api.db.command.inc(-1)
        }).then(res=>{
          wx.showToast({
            title: '已取消关注',
            icon:'none'
          });
        });
        // 重新获取数据
        this.getMyData();
      }else{
        wx.showToast({
          title: '操作失败，请重试',
          icon:'none'
        });
      }
    }
  }
})